package com.webserver.servlet;

import com.webserver.http.HttpRequest;
import com.webserver.http.HttpResponse;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.Arrays;

/**
 * 修改密码
 */
public class ChangePasswordServlet {
    public void service(HttpRequest request, HttpResponse response) {
        String name = request.getParameter("name");
        String pass = request.getParameter("pass");
        try (
                RandomAccessFile raf = new RandomAccessFile("user.dat", "rw");
        ) {
            for (int i = 0; i < raf.length() / 100; i++) {
                raf.seek(i * 100);
                byte[] data = new byte[32];
                raf.read(data);
                String username = new String(data, "utf-8").trim();
                if (username.equals(name)) {
                    byte[] passBytes = pass.getBytes("utf-8");
                    passBytes = Arrays.copyOf(passBytes, 32);
                    raf.write(passBytes);
                    System.out.println("修改成功");
                    File file = new File("./webapps/myweb/changepassword_success.html");
                    response.setEntity(file);
                    return;
                }
                break;
            }
            File file = new File("./webapps/myweb/changepassword_fail.html");
            response.setEntity(file);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
